package com.lysj.bhp.user.controller;


import com.lysj.bhp.investment.domain.Dividend;
import com.lysj.bhp.investment.domain.Reward;
import com.lysj.bhp.user.domain.BhpcEditLog;
import com.lysj.bhp.user.domain.WalletEditLog;
import com.lysj.bhp.user.util.MyWallet;
import com.lysj.bhp.user.vo.BhpcVo;
import com.lysj.bhp.util.random.FormatUtil;
import com.lysj.bhp.wallet.domain.BhpcWallet;
import com.lysj.bhp.wallet.domain.BitCoinWallet;
import com.lysj.bhp.wallet.domain.EthereumWallet;
import com.lysj.bhp.user.base.UserContent;
import com.lysj.bhp.user.domain.User;
import com.lysj.bhp.user.domain.UserEditLog;
import com.lysj.bhp.util.web.ParamUtil;
import com.lysj.bhp.util.web.Resp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.Bidi;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("admin/user_manager")
public class UserManagerController extends UserContent {
    private static Logger logger = LoggerFactory.getLogger(UserManagerController.class);

    @InitBinder
    public void InitBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }

    @Resource
    MyWallet myWallet;

    @GetMapping("/list")
    public Resp list(Integer limit, Integer offset, String search) {
        Integer page;
        if (ParamUtil.isBlack(limit)) {
            limit = 10;
        }
        if (ParamUtil.isBlack(offset)) {
            offset = 0;
        }
        if (search == null) {
            search = "";
        }
        page = offset / limit;
        Pageable pageable = new PageRequest(page, limit);

        String finalSearch = search;
        Specification specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> emailPath = root.get("email");
                query.where(cb.like(emailPath, "%" + finalSearch + "%"));
                return null;
            }
        };


        Page<User> userPage = userRepository.findAll(specification, pageable);

        Map<String, Object> respMap = new HashMap();
        respMap.put("total", userPage.getTotalElements());
        respMap.put("rows", userPage.getContent());
        return new Resp(respMap);
    }

    @PostMapping("/edit")
    public Resp edit(User model) {
        if (ParamUtil.isBlack(model.getUserId())) {
            return new Resp(Resp.PARAM_ERROR, "请选择用户id");
        }
        if (ParamUtil.isBlack(model.getEmail())) {
            return new Resp(Resp.PARAM_ERROR, "请选择邮箱");
        }
        if (ParamUtil.isBlack(model.getPhone())) {
            return new Resp(Resp.PARAM_ERROR, "请选择手机号");
        }
        if (ParamUtil.isBlack(model.getDividend())) {
            return new Resp(Resp.PARAM_ERROR, "请选择分红");
        }
        User user = userRepository.findOne(model.getUserId());
        user.setEmail(model.getEmail());
        user.setPhone(model.getPhone());
        user.setDividend(model.getDividend());
        userRepository.save(user);
        return new Resp("修改成功!");
    }


    @GetMapping("/bitcoin_wallet_detail")
    public Resp bitcoinWalletDetail(User model) {
        BitCoinWallet bitCoinWallet = bitcoinWalletRepository.findByUserId(model.getUserId());

        if (bitCoinWallet == null) {
            return new Resp(Resp.PARAM_ERROR, "该用户还没有创建比特币钱包");
        }
        bitCoinWallet.setBookKeepBalance(bitCoinWallet.getBookKeepBalance().setScale(6, BigDecimal.ROUND_DOWN));
        bitCoinWallet.setAvailBalance(bitCoinWallet.getAvailBalance().setScale(6, BigDecimal.ROUND_DOWN));
        bitCoinWallet.setBalance(bitCoinWallet.getBalance().setScale(6, BigDecimal.ROUND_DOWN));
        bitCoinWallet.setFreezeBalance(bitCoinWallet.getFreezeBalance().setScale(6, BigDecimal.ROUND_DOWN));

        return new Resp(bitCoinWallet);
    }

    @GetMapping("/etherum_wallet_detail")
    public Resp etherumWalletDetail(User model) {
        EthereumWallet ethereumWallet = ethereumWalletRepository.findByUserId(model.getUserId());

        if (ethereumWallet == null) {
            return new Resp(Resp.PARAM_ERROR, "该用户没有以太坊钱包");
        }
        //返回的钱包数额统一保留6位
        ethereumWallet.setBookKeepBalance(ethereumWallet.getBookKeepBalance().setScale(6, BigDecimal.ROUND_DOWN));
        ethereumWallet.setAvailBalance(ethereumWallet.getAvailBalance().setScale(6, BigDecimal.ROUND_DOWN));
        ethereumWallet.setBalance(ethereumWallet.getBalance().setScale(6, BigDecimal.ROUND_DOWN));
        ethereumWallet.setFreezeBalance(ethereumWallet.getFreezeBalance().setScale(6, BigDecimal.ROUND_DOWN));
        return new Resp(ethereumWallet);
    }

    /**
     * @author wtl
     * @date 2018-06-14 20:03
     * @Description :显示bhpc钱包详情
     */
    @GetMapping("/bhpc_wallet_detail")
    public Resp bhpcWalletDetail(User model) throws Exception {
        BhpcVo bhpcVo = new BhpcVo();
        BhpcWallet bhpcWallet = bhpcWalletRepository.findByUserId(model.getUserId());
        //若用户没有bhpc钱包,则给用户生成钱包,不生成钱包地址
        if (null == bhpcWallet) {
            bhpcWallet = myWallet.createBhpcWallet(model.getUserId());
        } else {
            bhpcVo.setAddress(bhpcWallet.getAddress());
        }
        //若用户没有奖励,则给用户生成奖励
        Reward reward = rewardRepository.findByUserId(model.getUserId());
        if (null == reward) {
            reward = new Reward();
            reward.setUserId(model.getUserId());
            reward.setType(100);
            reward.setBalance(new BigDecimal(BigInteger.ZERO));
            reward.setAvailBalance(new BigDecimal(BigInteger.ZERO));
            reward.setFreezeBalance(new BigDecimal(BigInteger.ZERO));
            rewardRepository.save(reward);
        }
        //bhpc钱包信息,保留6位小数返回前端显示
        bhpcVo.setBhpcBookKeepBalance(bhpcWallet.getBookKeepBalance().setScale(6, BigDecimal.ROUND_DOWN));
        bhpcVo.setBhpcAvailBalance(bhpcWallet.getAvailBalance().setScale(6, BigDecimal.ROUND_DOWN));
        bhpcVo.setBhpcBalance(bhpcWallet.getBalance().setScale(6, BigDecimal.ROUND_DOWN));
        bhpcVo.setBhpcFreezeBalance(bhpcWallet.getFreezeBalance().setScale(6, BigDecimal.ROUND_DOWN));
        bhpcVo.setAddress(bhpcWallet.getAddress());
        //bhpc奖励金,保留6位小数返回前端显示
        bhpcVo.setRewardBalance(reward.getBalance().setScale(6, BigDecimal.ROUND_DOWN));
        bhpcVo.setRewardAvailBalance(reward.getAvailBalance().setScale(6, BigDecimal.ROUND_DOWN));
        bhpcVo.setRewardFreezeBalance(reward.getFreezeBalance().setScale(6, BigDecimal.ROUND_DOWN));
        return new Resp(bhpcVo);
    }

    /**
     * @author wtl
     * @date 2018-06-14 20:03
     * @Description ：修改bhpc钱包的可用余额跟奖励金
     */
    @PostMapping("/update_bhpc_info")
    public Resp updateBhpcInfo(Long userId, BhpcEditLog bhpcEditLog) {
        return bhpcService.updateBhpcInfo(userId, bhpcEditLog);
    }


    /**
     * @author drj
     * @date 2018/06/22 16:51
     * @Description
     */
    @PostMapping("/transfers_money")
    public Resp transfersMoney(WalletEditLog model) throws Exception {

        if (null == model.getAmount()) {
            return new Resp(Resp.PARAM_ERROR, "请输入币量");
        }


        //walletType钱包类型:10:比特币;20:以太坊;100:BHPC;110:BHPC_Bouns;
        // operation操作方式:1增加,2减少
        switch (model.getWalletType()) {

            case 100:
                //查询用户的bhpc钱包
                BhpcWallet bhpcWallet = bhpcWalletRepository.findByUserId(model.getUserId());
                //若用户bhpc钱包不存在,
                if (null == bhpcWallet) {
                    //选择减少操作,则提示用户余额为0;选择增加操作,给用户创建钱包,同时更新钱包的总额跟可用余额
                    if (2 == model.getOperation()) {
                        return new Resp(Resp.PARAM_ERROR, "可用余额为0");
                    } else {
                        bhpcWallet = myWallet.createBhpcWallet(model.getUserId());
                        bhpcWallet.setAvailBalance(bhpcWallet.getAvailBalance().add(model.getAmount()));
                        bhpcWallet.setBalance(bhpcWallet.getBalance().add(model.getAmount()));
                        bhpcWalletRepository.save(bhpcWallet);
                    }
                } else {
                    //当选择减少币种该操作,判定用户的钱包数量是否足够
                    if (2 == model.getOperation()) {
                        //数量不足,返回提示;数量足够更新钱包余额
                        if (bhpcWallet.getAvailBalance().compareTo(model.getAmount()) == -1) {
                            return new Resp(Resp.PARAM_ERROR, "数量不足,最大只有" + bhpcWallet.getAvailBalance().setScale(6, BigDecimal.ROUND_DOWN) + "个");
                        } else {
                            bhpcWallet.setAvailBalance(bhpcWallet.getAvailBalance().subtract(model.getAmount()));
                            bhpcWallet.setBalance(bhpcWallet.getBalance().subtract(model.getAmount()));
                            bhpcWalletRepository.save(bhpcWallet);
                        }
                    } else {
                        //当选择增加币种该操作,更新钱包余额
                        bhpcWallet.setAvailBalance(bhpcWallet.getAvailBalance().add(model.getAmount()));
                        bhpcWallet.setBalance(bhpcWallet.getBalance().add(model.getAmount()));
                        bhpcWalletRepository.save(bhpcWallet);
                    }
                }
                break;
            case 110:
                //查询用户的奖励表
                Reward reward = rewardRepository.findByUserId(model.getUserId());
                //若用户奖励表不存在,
                if (null == reward) {
                    //选择减少操作,则提示用户余额为0;选择增加操作,给用户创建钱包,同时更新钱包的总额跟可用余额
                    if (2 == model.getOperation()) {
                        return new Resp(Resp.PARAM_ERROR, "可用余额为0");
                    } else {
                        reward = (Reward) myWallet.createReward(model.getUserId()).getObj();
                        reward.setAvailBalance(reward.getAvailBalance().add(model.getAmount()));
                        reward.setBalance(reward.getBalance().add(model.getAmount()));
                        rewardRepository.save(reward);
                    }
                } else {
                    //当选择减少币种该操作,判定用户的钱包数量是否足够
                    if (2 == model.getOperation()) {
                        //数量不足,返回提示;数量足够更新钱包余额
                        if (reward.getAvailBalance().compareTo(model.getAmount()) == -1) {
                            return new Resp(Resp.PARAM_ERROR, "数量不足,最大只有" + reward.getAvailBalance().setScale(6, BigDecimal.ROUND_DOWN) + "个");
                        } else {
                            reward.setAvailBalance(reward.getAvailBalance().subtract(model.getAmount()));
                            reward.setBalance(reward.getBalance().subtract(model.getAmount()));
                            rewardRepository.save(reward);
                        }
                    } else {
                        //当选择增加币种该操作,更新钱包余额
                        reward.setAvailBalance(reward.getAvailBalance().add(model.getAmount()));
                        reward.setBalance(reward.getBalance().add(model.getAmount()));
                        rewardRepository.save(reward);
                    }
                }
                break;

            case 20:
                //查询用户的eth钱包
                EthereumWallet ethereumWallet = ethereumWalletRepository.findByUserId(model.getUserId());
                //若用户eth钱包不存在,
                if (null == ethereumWallet) {
                    //选择减少操作,则提示用户余额为0;选择增加操作,给用户创建钱包,同时更新钱包的总额跟可用余额
                    if (2 == model.getOperation()) {
                        return new Resp(Resp.PARAM_ERROR, "可用余额为0");
                    } else {
                        ethereumWallet = (EthereumWallet) myWallet.createEthWallet(model.getUserId()).getObj();
                        ethereumWallet.setAvailBalance(ethereumWallet.getAvailBalance().add(model.getAmount()));
                        ethereumWallet.setBalance(ethereumWallet.getBalance().add(model.getAmount()));
                        ethereumWalletRepository.save(ethereumWallet);
                    }
                } else {
                    //当选择减少币种该操作,判定用户的钱包数量是否足够
                    if (2 == model.getOperation()) {
                        //数量不足,返回提示;数量足够更新钱包余额
                        if (ethereumWallet.getAvailBalance().compareTo(model.getAmount()) == -1) {
                            return new Resp(Resp.PARAM_ERROR, "数量不足,最大只有" + ethereumWallet.getAvailBalance().setScale(6, BigDecimal.ROUND_DOWN) + "个");
                        } else {
                            ethereumWallet.setAvailBalance(ethereumWallet.getAvailBalance().subtract(model.getAmount()));
                            ethereumWallet.setBalance(ethereumWallet.getBalance().subtract(model.getAmount()));
                            ethereumWalletRepository.save(ethereumWallet);
                        }
                    } else {
                        //当选择增加币种该操作,更新钱包余额
                        ethereumWallet.setAvailBalance(ethereumWallet.getAvailBalance().add(model.getAmount()));
                        ethereumWallet.setBalance(ethereumWallet.getBalance().add(model.getAmount()));
                        ethereumWalletRepository.save(ethereumWallet);
                    }
                }
                break;
            case 10:
                //查询用户的btc钱包
                BitCoinWallet bitCoinWallet = bitcoinWalletRepository.findByUserId(model.getUserId());
                //若用户btc钱包不存在,
                if (null == bitCoinWallet) {
                    //选择减少操作,则提示用户余额为0;选择增加操作,给用户创建钱包,同时更新钱包的总额跟可用余额
                    if (2 == model.getOperation()) {
                        return new Resp(Resp.PARAM_ERROR, "可用余额为0");
                    } else {
                        bitCoinWallet = (BitCoinWallet) myWallet.createBitWallet(model.getUserId(), model.getEmail()).getObj();
                        bitCoinWallet.setAvailBalance(bitCoinWallet.getAvailBalance().add(model.getAmount()));
                        bitCoinWallet.setBalance(bitCoinWallet.getBalance().add(model.getAmount()));
                        bitcoinWalletRepository.save(bitCoinWallet);
                    }
                } else {
                    //当选择减少币种该操作,判定用户的钱包数量是否足够
                    if (2 == model.getOperation()) {
                        //数量不足,返回提示;数量足够更新钱包余额
                        if (bitCoinWallet.getAvailBalance().compareTo(model.getAmount()) == -1) {
                            return new Resp(Resp.PARAM_ERROR, "数量不足,最大只有" + bitCoinWallet.getAvailBalance().setScale(6, BigDecimal.ROUND_DOWN) + "个");
                        } else {
                            bitCoinWallet.setAvailBalance(bitCoinWallet.getAvailBalance().subtract(model.getAmount()));
                            bitCoinWallet.setBalance(bitCoinWallet.getBalance().subtract(model.getAmount()));
                            bitcoinWalletRepository.save(bitCoinWallet);
                        }
                    } else {
                        //当选择增加币种该操作,更新钱包余额
                        bitCoinWallet.setAvailBalance(bitCoinWallet.getAvailBalance().add(model.getAmount()));
                        bitCoinWallet.setBalance(bitCoinWallet.getBalance().add(model.getAmount()));
                        bitcoinWalletRepository.save(bitCoinWallet);
                    }
                }
                break;
            default:
                break;
        }
        WalletEditLog walletEditLog = new WalletEditLog();
        walletEditLog.setUserId(model.getUserId());
        walletEditLog.setEmail(model.getEmail());
        walletEditLog.setEditDate(new Date());
        walletEditLog.setOperation(model.getOperation());
        walletEditLog.setWalletType(model.getWalletType());
        walletEditLog.setAmount(model.getAmount());
        walletEditLog.setReamrk(model.getReamrk());
        walletEditLog.setOperationName(currentStaff().getRealname());
        walletEditLogRepository.save(walletEditLog);

        return new Resp("修改成功");
    }


    @PostMapping("/reset_password")
    public Resp resetPassword(Long userId) {
        if (ParamUtil.isBlack(userId)) {
            return new Resp(Resp.PARAM_ERROR, "请选择用户");
        }
        User user = userRepository.findOne(userId);
        if (user == null) {
            return new Resp(Resp.PARAM_ERROR, "请选择用户");
        }
        user.setPassword(ParamUtil.md5("123456"));
        userRepository.save(user);
        return new Resp("重置密码成功!");
    }

    @PostMapping("/active")
    public Resp active(Long userId) {
        if (ParamUtil.isBlack(userId)) {
            return new Resp(Resp.PARAM_ERROR, "请选择用户");
        }
        User user = userRepository.findOne(userId);
        if (user == null) {
            return new Resp(Resp.PARAM_ERROR, "请选择用户");
        }
        if (user.getStatus() == 1) {
            return new Resp(Resp.PARAM_ERROR, "该用户已激活");
        }
        user.setStatus(1);
        userRepository.save(user);
        return new Resp("激活用户成功!");
    }


    @PostMapping("/lock_date")
    public Resp lockDate(Long userId, Date lockDate) {
        if (ParamUtil.isBlack(userId)) {
            return new Resp(Resp.PARAM_ERROR, "请选择用户");
        }
        User user = userRepository.findOne(userId);
        if (user == null) {
            return new Resp(Resp.PARAM_ERROR, "请选择用户");
        }
        if(null!=lockDate){
            user.setLockDate(FormatUtil.getDayEndDay(lockDate));
        }
        userRepository.save(user);
        return new Resp("修改成功!");
    }

}
